<html>
<head>
<#assign basePath=request.contextPath>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>新增审核</title>
    <!-- Bootstrap Core CSS -->
    <link href="${basePath}/bootstrap/css/bootstrap.min.css" rel="stylesheet">
    <link href="${basePath}/bootstrap/css/font-awesome.min.css" rel="stylesheet">
    <link href="${basePath}/bootstrap/css/form.lzy.css" rel="stylesheet">
    <link href="${basePath}/bootstrap/css/good.lzy.css" rel="stylesheet">
    <style>
        .select-box select {
            width: 150px;
            height: 30px;
            line-height: 30px;
        }

        .audit-box {
            padding-bottom: 20px;
        }

        .audit-box table {
            width: 450px;
            border-top: 1px solid #ccc;
            border-left: 1px solid #ccc;
        }

        .audit-box table tr {
        }

        .audit-box table th, .audit-box table td {
            text-align: center;
            border-bottom: 1px solid #ccc;
            border-right: 1px solid #ccc;
        }

        .audit-box table th {
            font-weight: bold;
        }

        .audit-box .super-btn {
            margin-left: 0;
        }

        .audit-box .super-box table {
            margin-bottom: 10px;
        }

        .audit .form-group {
            display: block;
            overflow: hidden;
            margin-top: 10px;
            margin-bottom: 0;
        }

        .audit h3 {
            margin-bottom: 10px;
        }

        .audit .super-box {
            width: 90%;
            height: 90%;
            margin: 20px auto 0;
            overflow: auto;
            position:absolute; left: 5%; top: 0;
        }

        .audit .super-box .table-responsive {
            width: 550px;
            margin-bottom: 10px;
        }

        .audit .super-box .table-responsive table {
            margin-bottom: 10px;
        }
    </style>
</head>
<body>
<div id="page-wrapper">
    <div class="panel">
        <div class="panel-body">
            <form id="myForm" class="form-horizontal" method="post" enctype="multipart/form-data">
                <input type="hidden" name="resourceId" id="resourceId">
                <div class="form-group">
                    <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 审核事件名：</span>
                    <div class="col-sm-9 col-xs-8">
                        <input type="text" class="form-control" size="30" name="name" id="name" value="" maxlength="20">
                    </div>
                </div>
                <div class="form-group">
                    <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 需审核的操作：</span>
                    <div class="col-sm-9 col-xs-8 select-box">
                        <select class="module" name="module">
                            <option value="">请选择</option>
                        </select>
                        <select class="list" name="list">
                            <option value="">请选择</option>
                        </select>
                        <select class="func" name="func">
                            <option value="">请选择</option>
                        </select>
                    </div>
                </div>
                <div class="form-group">
                    <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 审核流程：</span>
                    <div class="col-sm-9 col-xs-8 audit-box">
                        <input type="hidden" name="idArr" id="idArr" value="">
                        <input type="hidden" name="sortArr" id="sortArr" value="">
                        <input type="hidden" name="nameArr" id="nameArr" value="">
                        <input type="hidden" name="listType" id="listType" value="auditors">
                        <table border="0" class="table table-hover">
                            <thead>
                            <tr>
                                <th width="25%">审核排序</th>
                                <th width="50%">审核人</th>
                                <th width="25%">操作</th>
                            </tr>
                            </thead>
                            <tbody id="audit-con">
                            </tbody>
                        </table>
                        <span class="super-btn">添加审核人</span>
                    </div>
                </div>

                <div class="form-group">
                    <span class="control-label col-sm-2 col-xs-4"></span>
                    <div class="col-sm-9 col-xs-8">
                        <button type="button" class="btn btn-success" onclick="submitForm();"><i
                                class="fa fa-check"></i> 保存
                        </button>
                        <button type="button" class="btn btn-info" onclick="closePage();"><i class="fa fa-close"></i> 取消
                        </button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<!--审核人列表-->
<div class="super-bg audit">
    <div class="super-box">
        <h3>新增审核人<i class="fa fa-close"></i></h3>
        <form id="Form" class="form-horizontal">
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"><font color="red">*</font> 审核排序：</span>
                <div class="col-sm-9 col-xs-8">
                    <input type="text" class="form-control" size="30" name="sort" id="sort" value="" disabled>
                </div>
            </div>
            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"></span>
                <div class="col-sm-9 col-xs-8">
                    <div class="table-responsive">
                        <table width="95%" border="0" align="center"
                               id="myTable"
                               class="table table-hover"
                               data-pageSize="10,50,100" data-method="GET">
                            <thead>
                            <tr>
                                <th width="30%"></th>
                                <th width="35%">员工</th>
                                <th width="35%">电话</th>
                            </tr>
                            </thead>
                            <tbody id="tbodyId">

                            </tbody>
                        </table>
                        <span class="text-warning">同一级审核可设置多人，最少一人，最多三人</span>
                    </div>
                    <div class="row">
                        <div align="left" class="col-xs-4">
                            <div class="input-group">
                                <span class="input-group-addon" id="pageCount"></span> <select
                                    id="pageSize" onchange="reSearch(1)" class="form-control"
                                    style="width: 100px"></select>
                            </div>
                        </div>
                        <div align="right" class="col-xs-8">
                            <ul class="pagination" id="pagination"></ul>
                        </div>
                    </div>
                </div>
            </div>

            <div class="form-group">
                <span class="control-label col-sm-2 col-xs-4"></span>
                <div class="col-sm-9 col-xs-8 audit-btn">
                    <button type="button" class="btn btn-success"><i class="fa fa-check"></i> 保存</button>
                    <button type="button" class="btn btn-info"><i class="fa fa-close"></i> 取消</button>
                </div>
            </div>
            <br/> <br/>
        </form>
    </div>
</div>

<script src="${basePath}/bootstrap/js/jquery.min.js" type="text/javascript"></script>
<script src="${basePath}/bootstrap/js/bootstrap.min.js" type="text/javascript"></script>
<!-- layer JavaScript -->
<script src="${basePath}/bootstrap/plugin/layer/layer.js" type="text/javascript"></script>
<script type="text/javascript" src="${basePath}/bootstrap/plugin/jqPaginator/jqPaginator.js"></script>
<script type="text/javascript"
        src="https://cdn.bootcss.com/bootstrap-validator/0.5.3/js/bootstrapValidator.min.js"></script>
<script type="text/javascript">
    $(window).bootstrapValidator || document.write('<script src="${basePath}/bootstrap/js/bootstrapValidator.min.js"><\/script>');
</script>
<script>
    $(function () {
        //下拉框获取值
        var $mod = $(".select-box .module");
        var $list = $(".select-box .list");
        var $func = $(".select-box .func");
        $.ajax({
            type: "GET",
            url: "${basePath}/admin/resource/first/json?id=0",
            dataType: "json",
            async: "true",
            data: {},
            beforeSend: function () {
                layer.load(2);
            },
            success: function (data) {
                var temp = "";
                for (var i in data) {
                    temp += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
                }
                $mod.append(temp);
                layer.closeAll('loading');
            },
            error: function () {
                console.log("请求失败")
            }
        });
        $mod.change(function () {
            $list.html('<option value="">请选择</option>');
            var secId = $mod.val();
            if (secId) {
                $.ajax({
                    type: "GET",
                    url: "${basePath}/admin/resource/menu/json?id=" + secId,
                    dataType: "json",
                    async: "true",
                    data: {},
                    success: function (data) {
                        var temp = "";
                        for (var i in data) {
                            temp += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
                        }
                        $list.append(temp);
                    },
                    error: function () {
                        console.log("请求失败")
                    }
                });
            }
        });
        $list.change(function () {
            $func.html('<option value="">请选择</option>');
            var thirdId = $list.val();
            if (thirdId) {
                $.ajax({
                    type: "GET",
                    url: "${basePath}/admin/resource/func/json?id=" + thirdId,
                    dataType: "json",
                    async: "true",
                    data: {},
                    success: function (data) {
                        var temp = "";
                        for (var i in data) {
                            temp += "<option value='" + data[i].id + "'>" + data[i].name + "</option>"
                        }
                        $func.append(temp);
                    },
                    error: function () {
                        console.log("请求失败")
                    }
                });
            }
        })


        $(".super-btn").click(function () {
            //初始化下拉框
            $("#pageSize").empty();
            var data = $('#myTable').attr('data-pageSize').split(',');
            for (var i = 0; i < data.length; i++) {
                var option = $("<option>").text(data[i]).val(data[i]);
                $("#pageSize").append(option);
            }
            //定义查询选择框
            $.jqPaginator('#pagination', {
                totalPages: 100,
                visiblePages: 10,
                currentPage: 1,

                first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
                prev: '<li class="prev"><a href="javascript:void(0);">上一页<\/a><\/li>',
                next: '<li class="next"><a href="javascript:void(0);">下一页<\/a><\/li>',
                last: '<li class="last"><a href="javascript:void(0);">末页<\/a><\/li>',
                page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
                onPageChange: function (num) {
                    reSearch(num);
                }
            });
        });

    });
    var index = parent.layer.getFrameIndex(window.name); //获取窗口索引
    //关闭窗口并刷新页面
    function closePage() {
        parent.layer.close(index);
    }

    function reSearch(pageNum) {

        //选择推荐人
        var $spbox = $(".super-bg");
        var $tbody = $(".super-box table tbody");
        $spbox.show();
        $tbody.html("");
        //加载层
        layer.load(2);
        //获取form表单传入参数
        var jsonData = {};
        jsonData.begin = (pageNum - 1) * $('#pageSize').val();
        jsonData.rows = $('#pageSize').val();
        //计算当前页面
        jsonData.pageNum = pageNum;
        jsonData.pageSize = jsonData.rows;

        //搜索赋值
        var $spText = $("#listType");
        var key = $spText.attr("name");
        jsonData[key] = $spText.val();

        //获取数据
        $.ajax({
            type: "GET",
            url: "${basePath}/admin/manager/json",
            dataType: "json",
            async: "true",
            data: jsonData,
            success: function (data) {
                layer.closeAll('loading');
                $('#pageCount').html('当前总记录数:' + data.total);//显示记录数
                if (data.total > 0) {
                    //计算页数
                    if (data.total % $('#pageSize').val() > 0) {
                        var pageCount = (data.total - data.total % $('#pageSize').val()) / $('#pageSize').val() + 1;
                    } else {
                        var pageCount = data.total / $('#pageSize').val();
                    }

                    $('#pagination').jqPaginator('option', {
                        currentPage: pageNum, //当前页数
                        totalPages: pageCount //总页数
                    });

                    //拼接显示数据
                    var rows = data.rows;
                    var temp = "";
                    for (var i in rows) {
                        temp += "<tr><td style='display: none'>" + rows[i].id + "</td>" +
                                "<td width='15%' class='identity-add'><input type='checkbox' value='' name='programs[]'></td>" +
                                "<td width='25%'>" + rows[i].realName + "</td>" +
                                "<td width='25%'>" + rows[i].phone + "</td></tr>";
                    }
                    $tbody.append(temp);
                    ChooseVal();
                } else {
                    $('#pageCount').html('当前总记录数:0');//显示记录数
                    $('#pagination').jqPaginator('option', {
                        currentPage: 1, //当前页数
                        totalPages: 1 //总页数
                    });
                    $("#tbodyId").html('<tr align="center"><td colspan="' + $("#myTable").find("th").length + '">未查询到匹配的数据</td><tr>');
                }

                //设置统计结果
                if (typeof data.curPage != 'undefined') {
                    var cur = data.curPage;
                    for (var o in cur) {
                        $("#" + o + "_cur").text(cur[o]);
                    }
                }
                //设置统计结果
                if (typeof data.allPage != 'undefined') {
                    var cur = data.allPage;
                    for (var o in cur) {
                        $("#" + o + "_all").text(cur[o]);
                    }
                }

            },
            error: function () {
                console.log("error")
                //关闭加载层
                layer.closeAll('loading');
                $('#pageCount').html('当前总记录数:0');//显示记录数
                $("#tbodyId").html('<tr align="center"><td colspan="' + $("#myTable").find("th").length + '">未查询到匹配的数据</td><tr>');
            }
        });
        //关闭按钮
        $(".super-box .fa-close").click(function () {
            $spbox.hide();
            $tbody.html("");
        });

    };

    //选择函数
    var sort = 1;
    function ChooseVal() {
        var $sptr = $(".super-box table tbody tr");
        var $spbox = $(".super-bg");
        var $tbody = $(".super-box table tbody");
        var nameVal = [], idVal = [];
        $(".audit-btn .btn-info").click(function () {
            $spbox.hide();
        });
        sort = $("#audit-con tr").length + 1;
        $("#sort").val(sort);
        $(".audit-btn .btn-success").off("click").click(function () {
            //idArr.val("");
            var bsVal = $("#Form").data('bootstrapValidator');
            bsVal.validate();
            var len = $("#tbodyId input:checked").length;
            if (len > 3 || len < 1) {
                alert("同一级审核可设置最少一人、最多三人");
                return false;
            }
            else if (bsVal.isValid()) {
                //获取选中input对应的值
                $("#tbodyId input:checked").each(function () {
                    var curVal = $(this).parent().parent().find("td").eq(2).text();
                    var curId = $(this).parent().parent().find("td").eq(0).text();
                    nameVal.push(curVal);
                    idVal.push(curId);
                });
                var auditTr = "";
                for (var i = 0, j = 0; i < nameVal.length, j < idVal.length; i++, j++) {
                    auditTr += '<tr><td style="display: none">' + idVal[j] + '</td>' +
                            '<td width="25%">' + sort + '</td>' +
                            '<td width="50%">' + nameVal[i] + '</td>' +
                            '<td width="25%"><a href="#">删除</a></td></tr>'
                }

                $("#audit-con").append(auditTr);
                $("#idArr").val("17").change();//设定一个默认值 触发验证

                $spbox.hide();
                //sort++; //点击保存后排序加1
                nameVal = [];
                idVal = [];
            }
            //删除添加的
            trRemove();
        });
        //删除
        //trRemove();
//        $("#audit-con tr").each(function () {
//            $(this).find("td:last a").off("click").click(function () {
//                var _this = $(this).parent().parent();
//                _this.remove();
//            })
//        });
    }

    //删除
    function trRemove() {
        $("#audit-con tr").each(function () {
            $(this).find("td:last a").off("click").click(function (event) {
                event.preventDefault();
                var _this = $(this).parent().parent();
                var sort = _this.find("td").eq(1).text();
                var len = $("#audit-con tr." + sort).length;
                var lastId = $("#audit-con tr:last td").eq(1).text();
                console.log("sort:" + sort)
                console.log("lastId:" + lastId)
                if (sort == lastId) {
                    _this.remove();
                }
                else {
                    if (len > 1) {
                        _this.remove();
                    }
                    else {
                        alert("当前流程审核人至少需要设置一位！");
                        return false
                    }
                }

            })
        });
    }

    function submitForm() {
        var bsVal = $("#myForm").data('bootstrapValidator');
        bsVal.validate();
        if (bsVal.isValid()) {
            var sortArr = [];
            var idArr = [];
            var nameArr = [];
            $("#audit-con tr").each(function () {
                sortArr.push($(this).find("td").eq(1).text())
                idArr.push($(this).find("td").eq(0).text())
                nameArr.push($(this).find("td").eq(2).text())
            });
            $("#sortArr").val(sortArr);
            $("#idArr").val(idArr);
            $("#nameArr").val(nameArr);
            $("#resourceId").val($(".select-box .func").val());
            console.log($("#resourceId").val());
            $.ajax({
                method: 'POST',
                dataType: 'json',
                url: '${basePath}/admin/event/add',
                data: $("#myForm").serialize(),
                success: function (data) {
                    if (data.code == '0') {
                        layer.alert("操作成功", {
                            icon: 1
                        }, function () {
                            parent.layer.closeAll();
                        });
                    } else {
                        layer.alert(data.desc, {
                            icon: 56
                        });
                    }
                },
                error: function () {
                    layer.alert('系统错误', {
                        icon: 5
                    });
                }
            });
        }

    }

    $('#Form').bootstrapValidator({
        excluded: [":disabled"],
        fields: {
            sort: {
                validators: {
                    notEmpty: {
                        message: '请输入审核排序'
                    }
                }
            }
        }
    });
    $('#myForm').bootstrapValidator({
        excluded: [":disabled"],
        fields: {
            name: {
                validators: {
                    notEmpty: {
                        message: '请输入审核事件名'
                    }
                }
            },
            func: {
                validators: {
                    notEmpty: {
                        message: '请选择需审核的操作'
                    }
                }
            },
            idArr: {
                trigger: "change",
                validators: {
                    notEmpty: {
                        message: '请添加审核人'
                    }
                }
            }
        }
    })
</script>